module.exports = (EdtApi) => {
    "use strict";
    let chatId = "", accessToken = "", hmac = "", token = "", count = 0;
    function isGroup() {
        return !!document.querySelector(".chatroomHeader-module__member_count__s6hqu");
    }
    async function getChatId(times = 0) {
        let id = '', url = window.location.href;
        try {
            let urls = [];
            if (url.includes("friends/")) {
                urls = url?.split('friends/');
            } else if (url.includes("chats/")) {
                urls = url?.split('chats/');
            }
            id = urls.length > 1 ? urls[1] : '';
        } catch (error) {
            console.log('获取对话id失败', error)
        }
        if (id && id != chatId) return id;
        await EdtApi.sleep(50);
        if (times > 10) return id;
        times++;
        return getChatId(times);
    }
    function getAccessToken() {
        return new Promise((resolve, rejects) => {
            if (!hmac) hmac = localStorage.getItem("ed-line-x-hmac");
            if (!token) token = localStorage.getItem('ed-line-token');
            if (!token || !hmac) return rejects("请先播放语音消息！");
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.open("POST", "https://line-chrome-gw.line-apps.com/api/talk/thrift/Talk/TalkService/acquireEncryptedAccessToken", true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('x-line-chrome-version', '3.6.1');//谷歌插件版本号
            xhr.setRequestHeader('x-line-access', token);
            xhr.setRequestHeader('x-lal', "zh_CN");
            xhr.setRequestHeader('x-hmac', hmac);
            xhr.onload = function () {
                if (xhr.status === 200) {
                    // 处理成功响应
                    if (!xhr.responseText) {
                        console.error("下载文件时获取 accessToken 失败！");
                        rejects("获取语音文件失败！");
                    }
                    let json = JSON.parse(xhr.responseText);
                    if (json && json.data && 0 == json.code) {
                        accessToken = json.data.substring(7);
                    } else {
                        console.error("下载文件时获取 accessToken 失败！");
                        rejects("获取语音文件失败！");
                    }
                    resolve(accessToken);
                } else {
                    // 处理错误响应
                    console.error('请求失败：' + xhr.status);
                    rejects('获取语音文件失败:' + xhr.status)
                }
            };
            xhr.send("[2]");
        });
    }
    function downloadVoiceFile(msgId) {
        return new Promise((resolve, rejects) => {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "https://obs.line-apps.com/r/talk/m/" + msgId, true);
            xhr.setRequestHeader('X-Line-Application', 'CHROMEOS 3.6.1 Chrome_OS');//必须
            xhr.setRequestHeader('X-Line-Access', accessToken);
            xhr.responseType = "arraybuffer";
            xhr.onload = function () {
                if (xhr.status === 200) {
                    resolve(xhr.response)
                } else {
                    console.error('请求失败：' + xhr.status);
                    rejects('获取语音文件失败:' + xhr.status)
                }
            };
            xhr.send();
        });
    }
    function getVoiceFile(msgId) {
        return new Promise((resolve, rejects) => {
            getAccessToken().then(() => {
                downloadVoiceFile(msgId).then(voiceFile => {
                    if (voiceFile) {
                        resolve(voiceFile)
                    } else {
                        rejects("获取语音文件失败！")
                    }
                }).catch((err) => {
                    rejects("获取语音文件失败！")
                });
            }).catch((err) => {
                rejects(err);
            });
        });
    }
    return {
        config: {
            friendList: 'div.friendlist-module__list__Z-8nt,div.chatlist-module__chatlist__qruAE',
            chat: '#root div.chatroom-module__chatroom__eVUaK',
            input: '.chatroomEditor-module__textarea__yKTlH',
            msgBox: "div.chatroomContent-module__content_area__gK6db>div.message_list",
            inMsg: 'div.messageLayout-module__message__YVDhk:not([data-direction="reverse"]) .textMessageContent-module__text__EFwEN:not(.trans-inited)',
            outMsg: 'div.messageLayout-module__message__YVDhk[data-direction="reverse"] .textMessageContent-module__text__EFwEN:not(.trans-inited)',
            allMsg: 'div.messageLayout-module__message__YVDhk .textMessageContent-module__text__EFwEN',
            voiceMsg: '.audioMessageContent-module__play_info__tmjOL:not(.trans-inited)',
            outVoice: {
                selector: 'div.messageLayout-module__message__YVDhk[data-direction="reverse"]',
                level: 10,
            },
            setting: '.actionGroup-module__action_box__-HA8N button.actionGroup-module__button_action__VwNgx[data-type="sticker"]',
            tips: {
                in: 'div.chatroomHeader-module__header__ihDT2>div.chatroomHeader-module__inner__0P5fp',
                out: 'div.chatroomEditor-module__editor_area__1UsgR'
            },
            crm: {
                // listener: '#LeftColumn-main',
                top: '#root div.chatroom-module__chatroom__eVUaK button[aria-controls="member_popup"]',
                left: ""
            },
            inputType: "input",
            contextmenu: false,
            placeholder: {
                selector: ".chatroomEditor-module__textarea__yKTlH",
                attr: "placeholder",
                delay: 200,
                update: true
            },
            autoCount: 20,
            noSkipChinese: true,
            showNotifyInMain: true
        },
        init() {
            this.setToken();//特殊
        },
        getAllMsg(box = document) {//line消息列表特殊，元素列表中最新的在最上面
            let allMsg = box.querySelectorAll(this.config.allMsg);
            allMsg = Array.prototype.slice.call(allMsg);
            allMsg.reverse();
            return allMsg;
        },
        getUnread() {
            count = document.querySelector('.badge-module__badge__Eh36I')?.textContent || 0;
            return EdtApi.safeParseInt(count);
        },
        getChatInfo() {
            return new Promise(async (resolve) => {
                chatId = await getChatId();
                resolve({ id: chatId, isGroup: isGroup() });
            });
        },
        getChatTitle(chatEl = document) {
            let titleEl = chatEl.querySelector('button[aria-controls="member_popup"]>strong.chatroomHeader-module__name__t-K11>pre>span');
            if (!titleEl) return "";
            if (!titleEl.querySelector('.emoji')) return titleEl.textContent || '';
            let title = "";
            titleEl.childNodes?.forEach(child => {
                if (child.nodeName == '#text') {
                    title += child.textContent || "";
                } else if (child.nodeName == 'IMG') {
                    title += child.alt || "";
                }
            });
            return title;
        },
        getText(msgBox) {
            return msgBox ? msgBox.textContent : "";
        },
        getIptMsg(inputEl) {
            if (!inputEl) return '';
            let realTextarea = inputEl.shadowRoot && inputEl.shadowRoot.querySelector('textarea');
            return realTextarea?.value;
        },
        setToken() {
            EdtApi.setToken({
                url: "https://line-chrome-gw.line-apps.com",
                name: "lct",
                value: localStorage.getItem('ed-line-token'),
            });
        },
        inputMsg(inputEl, msg) {
            return new Promise((resolve) => {
                let realTextarea = inputEl.shadowRoot && inputEl.shadowRoot.querySelector('textarea');
                realTextarea.value = msg;
                inputEl.value = [msg];
                const evt = document.createEvent('HTMLEvents');
                evt.initEvent('input', true, true);
                realTextarea.dispatchEvent(evt);
                inputEl.dispatchEvent(evt);
                resolve(true);
            });
        },
        getVoice(msgBox) {
            return new Promise((resolve, reject) => {
                let msgId = this.getMsgId(msgBox);
                getVoiceFile(msgId).then(file => {
                    resolve({
                        file,
                        msgId,
                        type: "audio/x-m4a",
                        name: `${msgId}.m4a`
                    });
                }).catch((err) => {
                    reject(err?.message || "获取语音文件失败！");
                });
            });
        },
        getMsgId(msgBox) {
            let message = EdtApi.closest(msgBox, "div[data-message-id]", 5);
            return message?.getAttribute("data-message-id");
        },
        getUserInfo() {
            try {
                let globalData = JSON.parse(localStorage.getItem('lcs_plain_common') || '{}');
                let info = globalData?.settings;
                let account = info?.lastLoggedInEmail || "";
                let userEl = document.querySelector("div.friendlist-module__inner__d3xFH div.friendlistItem-module__item__1tuZn");
                let avatar = "";
                let userName = "";
                if (userEl) {
                    let avatarEl = userEl.querySelector("button.profileImage-module__button_profile__GqKue img");
                    avatar = avatarEl?.getAttribute("src");
                    let userNameEl = userEl.querySelector("div.friendlistItem-module__info__89Stz span.friendlistItem-module__text__YxSko");
                    userName = userNameEl?.textContent;
                    if (!account) account = userName;
                }
                return {
                    avatar,
                    userName,
                    account,
                    toDataUrl: true
                };
            } catch (error) {
                return null;
            }
        }
    }
};